package cn.edu.cumt.ec.shop.exception;

import cn.edu.cumt.ec.shop.entity.Result;
import cn.edu.cumt.ec.shop.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class ControllerExceptionAdvice {

    Logger logger = LoggerFactory.getLogger(getClass());

    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Result handlerException(HttpServletRequest request, CustomException customException){
        String requestURI = request.getRequestURI();
        logger.error("请求地址'{}',发生自定义异常.", requestURI, customException);
        //具体返回什么HttpStatus，可由customException决定
        //为了统一处理，异常的状态码为500 ，成功为200
        return ResultUtil.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),customException.getMessage());
    }
}
